<template>
  <t-modal
    :title="subtitle"
    width="1224px"
    :visible="visible"
    @cancel="closeModal()"
    wrapClassName="move-modal-container"
    forceRender
    v-bind="footer"
  >
    <div class="curve-modal-body">
      <div class="contents-warp">
        <a-empty v-if="treeData.length == 0" :description="false" />
        <a-tree
          v-else
          show-icon
          show-line
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :selected-keys="selectedKeys"
          :tree-data="treeData"
          :replaceFields="{
            children: 'children',
            title: 'nodeName',
            key: 'uuid',
          }"
          @expand="onExpand"
          @select="onSelect"
        >
          <!-- 自定义图标 -->
          <template slot="custom" slot-scope="{ expanded }">
            <a-icon
              :type="expanded ? 'folder-open' : 'folder'"
              theme="filled"
            />
          </template>
          <template slot="title" slot-scope="{ nodeName }">
            <div class="custom-tree-title-warp">
              <div class="title" :title="nodeName">
                {{ nodeName }}
              </div>
            </div>
          </template>
        </a-tree>
      </div>
      <div class="files-warp">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="tableLoading"
        >
          <vxe-column type="seq" width="80" title="序号"> </vxe-column>
          <vxe-column
            field="fileName"
            title="文件名称"
            align="left"
            min-width="300"
          >
            <template #default="{ row }">
              <div class="table-file-name">
                <div
                  class="icon"
                  :class="[getFileIconName(row.fileName)]"
                ></div>
                <div class="name" @click="previewFile(row)">
                  {{ row.fileName }}
                </div>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="creator" title="上传人"> </vxe-column>
          <vxe-column field="createTime" title="上传时间"> </vxe-column>
          <vxe-column field="operate" fixed="right" width="60" title="操作">
            <template #default="{ row }">
              <div class="files-icon">
                <!-- 下载 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon type="download" @click="downloadFile(row, 1)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import {
  addAttributeByKey,
  flatTreeData,
  getNodeByKey,
  getFileIconName,
} from "@/utils/util.js";
import {
  getToken,
  downloadDfs,
  downLoadBatchFileByArraybuffer,
} from "@/utils/TopVUI";

import cloneDeep from "lodash.clonedeep";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
export default {
  components: {
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    dataSource: {
      type: Object,
      default: () => {
        return {};
      },
    },
    subtitle: {
      type: String,
      default: "查看/下载",
    },
  },
  data() {
    return {
      footer: { footer: null },
      //
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
      //表格
      tableData: [],
      tableLoading: false,
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getTreeData();
        }
      },
      immediate: true,
    },
  },

  methods: {
    getFileIconName,

    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.currentTreeNode = info.node.dataRef;
      this.getTableData();
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    getTreeData() {
      let { classifyId, uuid } = this.dataSource;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/designBriefing/getTreeByProCodeInnerPage`,
            {
              uuid,
              classifyId,
            },
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            let flatData = flatTreeData(this.cloneTreeData, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "children"
            );
            this.treeData = filterData ?? [];
            this.currentTreeNode = this.treeData?.[0] ?? [];
            this.selectedKeys = [this.currentTreeNode.uuid];
            this.getTableData();
            resolve();
          })
          .catch((_) => {
            this.expandedKeys = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    getTableData() {
      let { uuid } = this.dataSource;
      let { id } = this.currentTreeNode;
      this.tableLoading = true;
      axios
        .post(
          `/probusiness/bimCadFile/getListByForeignKey`,
          {
            classifyId: id,
            type: 10,
            uuid,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.tableData = data ?? [];
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //交底文件预览
    previewFile(row) {
      let { previewWay, uuid, fileInfo, unit, bhDataSetId } = row;
      let { fileName } = fileInfo;
      let domain = location.origin;
      switch (previewWay) {
        //cad预览
        case "cad":
          window.open(
            `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
          );
          return;
        // 模型预览
        case "model":
          bhDataSetId &&
            window.open(
              `${domain}/#/blackHole/viewDataSetSingleSimple?dataSetId=${bhDataSetId}&name=${fileName}`
            );
          return;
        // 普通文件预览
        case "kkview":
          this.viewFile(fileInfo);
          return;
        default:
          break;
      }
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //下载
    downloadFile(row, type) {
      //引用文件
      if (type == 1) {
        let { fileInfo } = row;
        // 创建一个<a>元素
        const link = document.createElement("a");
        // 设置文件的URL
        link.href = fileInfo.url;
        // 设置下载后的文件名
        link.download = fileInfo.fileName;
        // 将<a>元素添加到页面中
        document.body.appendChild(link);
        // 模拟点击<a>元素
        link.click();
        // 移除<a>元素
        document.body.removeChild(link);
      }
      //交底记录、图纸
      else {
        let { url } = row;
        downloadDfs(url);
      }
    },

    //关闭弹窗
    closeModal() {
      this.expandedKeys = [];
      this.autoExpandParent = true;
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.currentTreeNode = {};
      this.tableData = [];
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.move-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 12px 12px;
      height: 620px;
      display: flex;
      overflow: hidden;
      .contents-warp {
        width: 300px;
        flex-shrink: 0;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d4d7d8;
        overflow: auto;
        overflow-x: hidden;
        padding: 10px;
        box-sizing: border-box;
        position: relative;
        .ant-empty {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
        .ant-tree {
          li {
            width: 100%;
            .ant-tree-node-content-wrapper {
              position: relative;
              width: calc(100% - 25px);
              padding: 0;
              .ant-tree-iconEle {
                color: #ffca28;
                font-size: 16px;
              }
              .ant-tree-title {
                overflow: hidden;
                display: inline-block;
                width: calc(100% - 26px);
                .custom-tree-title-warp {
                  display: flex;
                  width: 100%;
                  .title {
                    flex: 1;
                    overflow: hidden;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  }
                  .operate {
                    flex-shrink: 0;
                  }
                }
              }
            }
          }
        }
      }
      .files-warp {
        width: calc(100% - 310px);
        margin-left: 10px;
        .files-icon {
          .anticon {
            cursor: pointer;
            font-size: 18px;
            color: #1677ff;
            margin-right: 16px;
            &:last-of-type {
              margin-right: 0;
            }
          }
          .anticon-download {
            color: #239b53;
          }
          .anticon-delete {
            color: #e43d3d;
          }
        }
      }
    }
  }
}
</style>
